package com.leil.fileserver.controller;

import com.alibaba.fastjson.JSONObject;
import com.leil.fileserver.exception.FileOptException;
import com.leil.fileserver.service.ImageUploadService;
import com.leil.fileserver.service.VoiceUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


@RestController
@RequestMapping("/upload")
public class FileUploadController {

    @Autowired
    ImageUploadService imageUploadService;

    @Autowired
    VoiceUploadService voiceUploadService;

    @PostMapping("/img")
    public JSONObject uploadImage(@RequestParam("file") MultipartFile file) {
        JSONObject json = new JSONObject();
        try {
            String imgUrl = this.imageUploadService.Upload(file, true);
            json.put("code", 200);
            json.put("imgUrl", imgUrl);
        } catch (FileOptException e) {
            json.put("code", 500);
            json.put("errMsg", e.getMessage());
        }
        return json;
    }


    @PostMapping("/voice")
    public JSONObject uploadVoice(@RequestParam("file") MultipartFile file) {
        JSONObject json = new JSONObject();
        try {
            String voiceUrl = this.voiceUploadService.Upload(file, false);
            json.put("code", 200);
            json.put("voiceUrl", voiceUrl);
        } catch (FileOptException e) {
            json.put("code", 500);
            json.put("errMsg", e.getMessage());
        }
        return json;
    }


}
